import type { ColEx } from '../types';
import type { AdvanceState } from '../types/hooks';
import { ComputedRef, Ref, ref } from 'vue';
import type { FormProps, FormSchema } from '../types/form';
import {
  // computed,
  unref,
  watch,
} from 'vue';
import {
  isBoolean,
  isFunction,
  //  isNumber, isObject
} from '/@/utils/is';
import { useBreakpoint } from '/@/hooks/event/useBreakpoint';
import { useDebounceFn } from '@vueuse/core';

const BASIC_COL_LEN = 24;

interface UseAdvancedContext {
  advanceState: AdvanceState;
  emit: EmitType;
  getProps: ComputedRef<FormProps>;
  getSchema: ComputedRef<FormSchema[]>;
  formModel: Recordable;
  defaultValueRef: Ref<Recordable>;
}

export default function ({
  advanceState,
  emit,
  getProps,
  getSchema,
  formModel,
  defaultValueRef,
}: UseAdvancedContext) {
  const {
    realWidthRef,
    screenEnum,
    //screenRef
  } = useBreakpoint();
  const searchWidth = ref<any>({
    xxl: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
    xl: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
    lg: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
    md: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
    sm: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
    xs: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
    span: { row: 'calc(100% - 170px)', col: 'calc(100% - 178px)' },
  });
  // const getEmptySpan = computed((): number => {
  //   if (!advanceState.isAdvanced) {
  //     return 0;
  //   }
  //   // For some special cases, you need to manually specify additional blank lines
  //   const emptySpan = unref(getProps).emptySpan || 0;

  //   if (isNumber(emptySpan)) {
  //     return emptySpan;
  //   }
  //   if (isObject(emptySpan)) {
  //     const { span = 0 } = emptySpan;
  //     const screen = unref(screenRef) as string;

  //     const screenSpan = (emptySpan as any)[screen.toLowerCase()];
  //     return screenSpan || span || 0;
  //   }
  //   return 0;
  // });

  const debounceUpdateAdvanced = useDebounceFn(updateAdvanced, 30);

  watch(
    [() => unref(getSchema), () => unref(realWidthRef)],
    () => {
      const { showAdvancedButton } = unref(getProps);
      if (showAdvancedButton) {
        debounceUpdateAdvanced();
      }
    },
    { immediate: true },
  );

  function compulateSearchWidth(obj, itemColSum) {
    const tablewidth = unref(getProps).tableWidth;

    // const curObj = { xxl: 0, xl: 0, xs: 0, sm: 0, md: 0, lg: 0, span: 0 };
    // const width = unref(realWidthRef);

    //const curSpan = obj.span;
    // schema.forEach((o) => {
    //   if (o.isAdvanced) {
    //     for (const i in o.colProps) {
    //       obj[i] += o.colProps[i] ? Number(o.colProps[i]) : baseColProps[i];
    //     }
    //   }
    // });

    // if (width > screenEnum.XS) {
    //   curSpan = obj.xs ? Number(obj.xs) : curSpan;
    // }
    // if (width > screenEnum.SM) {
    //   curSpan = obj.sm ? Number(obj.sm) : curSpan;
    // }
    // if (width > screenEnum.MD) {
    //   curSpan = obj.md ? Number(obj.md) : curSpan;
    // }
    // if (width > screenEnum.LG) {
    //   curSpan = obj.lg ? Number(obj.lg) : curSpan;
    // }
    // if (width > screenEnum.XL) {
    //   curSpan = obj.xl ? Number(obj.xl) : curSpan;
    // }
    // if (width > screenEnum.XXL) {
    //   curSpan = obj.xxl ? Number(obj.xxl) : curSpan;
    // }

    for (const i in obj) {
      let str = '100%';
      let row = '100%';
      if (((24 - itemColSum) / 24) * tablewidth >= 178 || itemColSum >= 24) {
        str = '(100% - 178px)';
        row = '(100% - 178px)';
      }
      searchWidth.value[i].row = 'calc(' + row + ')';

      searchWidth.value[i].col = 'calc(' + str + ' * ' + itemColSum / 24 + ')';
    }
  }
  function getAdvanced(
    itemCol: Partial<ColEx>,
    itemColSum = 0,
    //isLastAction = false
  ) {
    const width = unref(realWidthRef);

    const spanWidth = itemCol.span as number;
    const xsWidth = spanWidth || parseInt(itemCol.xs as number) || 24;
    const smWidth = spanWidth || parseInt(itemCol.sm as number) || 12;
    const mdWidth = spanWidth || parseInt(itemCol.md as number) || 8;
    const lgWidth = spanWidth || parseInt(itemCol.lg as number) || 8;
    const xlWidth = spanWidth || parseInt(itemCol.xl as number) || 8;
    const xxlWidth = spanWidth || parseInt(itemCol.xxl as number) || 8;
    const widthObj = {
      span: spanWidth,
      xs: xsWidth,
      sm: smWidth,
      md: mdWidth,
      lg: lgWidth,
      xl: xlWidth,
      xxl: xxlWidth,
    };
    if (width <= screenEnum.XS) {
      itemColSum += xsWidth;
    } else if (width > screenEnum.XS && width <= screenEnum.SM) {
      itemColSum += xsWidth;
    } else if (width > screenEnum.SM && width <= screenEnum.MD) {
      itemColSum += smWidth;
    } else if (width > screenEnum.MD && width <= screenEnum.LG) {
      itemColSum += mdWidth;
    } else if (width > screenEnum.LG && width <= screenEnum.XL) {
      itemColSum += lgWidth;
    } else if (width > screenEnum.XL && width <= screenEnum.XXL) {
      itemColSum += xlWidth;
    } else {
      itemColSum += xxlWidth;
    }

    // if (isLastAction) {
    advanceState.hideAdvanceBtn = false;

    if (itemColSum <= BASIC_COL_LEN) {
      // When less than or equal to 2 lines, the collapse and expand buttons are not displayed
      advanceState.hideAdvanceBtn = true;
      advanceState.isAdvanced = true;
      compulateSearchWidth(widthObj, itemColSum);
    } else if (itemColSum > BASIC_COL_LEN) {
      advanceState.hideAdvanceBtn = false;
      advanceState.isAdvanced = false;

      // More than 3 lines collapsed by default
    } else if (!advanceState.isLoad) {
      advanceState.isLoad = true;
      advanceState.isAdvanced = !advanceState.isAdvanced;
    }
    return { isAdvanced: true, itemColSum };
    //}

    // if (itemColSum > BASIC_COL_LEN * (unref(getProps).alwaysShowLines || 1)) {
    //   return { isAdvanced: advanceState.isAdvanced, itemColSum };
    // }
    // else {
    //   // The first line is always displayed
    //   return { isAdvanced: true, itemColSum };
    // }
  }

  function updateAdvanced() {
    let itemColSum = 0;
    // let realItemColSum = 0;
    const { baseColProps = {} } = unref(getProps);

    for (const schema of unref(getSchema)) {
      const { show, colProps } = schema;
      let isShow = true;

      if (isBoolean(show)) {
        isShow = show;
      }

      if (isFunction(show)) {
        isShow = show({
          schema: schema,
          model: formModel,
          field: schema.field,
          values: {
            ...unref(defaultValueRef),
            ...formModel,
          },
        });
      }

      if (isShow && (colProps || baseColProps)) {
        const { itemColSum: sum, isAdvanced } = getAdvanced(
          { ...baseColProps, ...colProps },
          itemColSum,
        );

        itemColSum = sum || 0;
        // if (isAdvanced) {
        //   realItemColSum = itemColSum;
        // }
        schema.isAdvanced = isAdvanced;
      }
    }

    // advanceState.actionSpan = (realItemColSum % BASIC_COL_LEN) + unref(getEmptySpan);

    // getAdvanced(unref(getProps).actionColOptions || { span: BASIC_COL_LEN }, itemColSum, true);

    emit('advanced-change');
  }

  function handleToggleAdvanced() {
    advanceState.isAdvanced = !advanceState.isAdvanced;
  }

  return { handleToggleAdvanced, searchWidth };
}
